package client.ui;

import client.network.BanchoClient;
import common.Callback;
import common.enums.RequestType;
import common.requests.Request;
import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.scene.text.Text;
import server.Bancho;

import java.io.File;
import java.io.FileNotFoundException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.Scanner;

public class loginUIController implements Initializable, ControlledStage, Callback{
    stageController theStageController;          //StageController属性（域、字段）

    @FXML private TextField  accountNumber;    //账号输入框
    @FXML private PasswordField key;           //密码输入框

    @FXML private CheckBox rememberKey;        //记住密码勾选框

    @FXML private Button loginButton;          //登录Button

    @FXML private Text registerAccount;        //注册账号

    @FXML public Button visibleButton;

    /*-----------------------------创建文件保存状态---------------------------------*/
    File fileName = new File("F:\\TTsave.txt");

    public void createFile(File file)throws Exception{
        if (!file.exists())
            file.createNewFile();
    }


    /*-----------------------------设置舞台控制器-----------------------------------*/
    //设置StageController属性的方法
    public void setStageController(stageController stageController){
        theStageController = stageController;
    }

    /*-----------------------------初始化接口的实现---------------------------------*/
    @Override
    @FXML
    public void initialize(URL location, ResourceBundle resources) {
        try {
            createFile(fileName);
        } catch (Exception e) {
            e.printStackTrace();
        }

        BanchoClient.addCallback(this);

        //从保存文件返回是否记住密码的状态，如果有的话就返回账号密码; 同样从保存文件返回是否自动登录的状态
        //从文件中读取状态、账号和密码
        try {
            Scanner input = new Scanner(fileName);
            if (Integer.parseInt(input.nextLine()) == 1){
                rememberKey.setSelected(true);
                accountNumber.setText(input.nextLine());
                key.setText(input.nextLine());
            }
            input.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    /*-------------------------------记住密码---------------------------------------*/
    //每次登录的时候都要返回
    @FXML void isSelected() throws FileNotFoundException {
        java.io.PrintWriter output = new java.io.PrintWriter(fileName);
        if (rememberKey.isSelected()){
            output.println(1);
            //long a = Long.parseLong(accountNumber.getText());
            output.println(accountNumber.getText());
            output.println(key.getText());
        } else{
            output.print(0);
        }
        output.close();
    }

    /*-------------------------------BUTTON-----------------------------------------*/
    boolean logging = false;
    @FXML protected void handleLoginButtonAction(){
        if (logging) return;
        logging = true;
        if (true) {
            Map<String, Object> map = new HashMap<>();
            map.put("uid", accountNumber.getText());
            map.put("password", key.getText());
            BanchoClient.SendRequest(RequestType.User_Login, map);
        }
    }

    /*-------------------------------注册-------------------------------------------*/
    @FXML protected void mouseEnterAction(){
        //样式

        registerAccount.setStyle("-fx-background-color: aqua");
    }

    @FXML protected void mouseClickedAction(){
        theStageController.setStage("registerWindows","loginWindows");
    }

    /*-----------------------------处理网络请求-------------------------------------*/
    @Override
    public void callback(Request request) {
        Platform.runLater(() -> {
            if (request.type == RequestType.User_LoginResult) {
                if (Long.parseLong(request.payload.get("result").toString()) > 0) {
                    BanchoClient.user.username = request.payload.get("username").toString();
                    visibleButton.setText(request.payload.get("username").toString());

                    BanchoClient.user.id = Long.parseLong(request.payload.get("result").toString());
                    loginButton.setText("logining");
                    theStageController.setStage("primaryWindows", "loginWindows");
                    BanchoClient.removeCallback(this);
                }  else {
                    //弹出警示框，密码或者账号错误，message要陈述原因
                    String message = "账号或者密码错误！";
                    Alert alertWindow = new Alert(Alert.AlertType.INFORMATION, message);
                    alertWindow.setTitle("警告");
                    alertWindow.setHeaderText("登录失败");
                    alertWindow.show();
                }
            }
        });
    }
}
